<template>
    <div class="formBox" style="width: 100%;height:100%;">
        <bpm-header :title="processConfig.name" :version="version"></bpm-header>
        <div style="height: calc( 100% - 50px );">
            <a-tabs class="rx-bpm-tabs" default-active-key="details" @change="changeTabs($event)">
                <template #rightExtra>
                    <div class="tabs-toolbar">
                        <process-tool-bar
                            ref="processToolBar"
                            v-if="!preview"
                            :processConfig="processConfig"
                            :def-id="localDefId"
                            :instId="instId"
                            :mainDefId="mainDefId"
                            :mainTaskId="mainTaskId"
                            :bpmActionType="'bpmInstStart'"
                            :vars="vars"/>
                        <a-button v-else @click="bpmPreview">{{ $ti18('rxForm.commitBtn', '提交') }}</a-button>
                    </div>
                </template>
                <a-tab-pane key="details" :tab="i18n('list.detail', '详情')">
                    <div class="tab-center-bg">
                        <div class="tab-center-box" >
                            <rx-forms v-if="processConfig.formType=='online'" ref="rxForms"></rx-forms>
                            <component v-else-if="processConfig.formType=='custom'"
                                       ref="customForm" :is="formComponent"
                                       :params="urlParamData"
                                       :pk="pk"></component>

                            <url-view v-else-if="processConfig.formType=='outsideUrl' " ref="outSideUrlForm"   :pk="pk"
                                       :showUrl="outSideUrl" :urlParamData="urlParamData"></url-view>
                        </div>
                    </div>
                </a-tab-pane>
                <a-tab-pane key="flowChart" :tab="i18n('list.flowChart', '流程图')">
                    <bpm-image-view v-if="isShowImage" :def-id="localDefId" :formData="formDataJson"/>
                </a-tab-pane>
            </a-tabs>
        </div>

    </div>
</template>
<script>
import {RxFit, Util} from '@lowcode/jpaas-base-lib';
import ProcessToolBar from "./ProcessToolBar.vue";
import BpmInstApi from "@/common/api/bpm/bpmInst";
import RxForms from "./RxForms.vue";
import {BpmImageView} from '@lowcode/jpaas-share-component';
import FlowUtil from "../js/FlowUtil.js";
import bpmHeader from "./bpmHeader.vue";
import useMain from "@/stores/useMain";
import {mapState} from 'pinia';
import userUser from "@/stores/userUser";
import UrlView from "@/views/modules/form/FormCustomView/components/ColumnView/UrlView.vue";
import UrlParamsUtil from "@/views/modules/bpm/OpenDoc/js/url-params-util";
import AppUtil from "@/assets/js/AppUtil"


export default {
    name: "bpm-inst-start",
    mixins: [FlowUtil,UrlParamsUtil],
    computed: {
        ...mapState(useMain, ['appKey']),
        ...mapState(userUser, ['user'])
    },
    props: {
        //流程定义ID
        defId: String,
        //流程实例ID
        instId: {
            type: String,
            default: ""
        },
        //通过主键直接启动流程
        pkId: String,
        //这个是从DialogView打开时需要用到的。
        menuParams: {
            type: String
        },

        mainDefId: String,
        mainTaskId: String,
        formData: Object,
        vars: Object,

        layerid: String,
        destroy: Function,
        config: Object,
        preview: Boolean,
        startUserId: String
    },
    components: {
        UrlView,
        ProcessToolBar,
        RxFit, bpmHeader,
        RxForms, BpmImageView
    },
    data() {
        var hasPk = false;
        if (this.pkId) {
            hasPk = true;
        }
        return {
            version: 1,
            closed: false,
            title: this.i18n('list.processInit', '流程发起'),
            processConfig: {
                buttons: [],
                startConfirm: false,
                fillOpinion: false,
                assignFlowUsers: false,
                assignBatchFlowUsers: false,
                startCalFlowusers: false,
                //是否允许选择路径。
                allowSelectPath: false,
                formType: "online",
                hasPk: hasPk
            },
            pk: "",
            //流程定义KEY
            defKey: "",
            //流程定义ID
            localDefId: "",
            //是否从路由过来
            fromRoute: false,
            //根实例
            rootVm: true,
            formDataJson: {},
            isShowImage: false,

            outSideUrl: "",
            urlParamData: {},
            //自定义表单组件
            formComponent:{},
            //幂等号
            idempotenceid:""
        }
    },
    created() {
        this.initParams();
    },
    methods: {
        changeTabs(key) {
            if (key == 'flowChart') {
                this.getFormData();
            } else {
                this.isShowImage = false;
            }
        },
        getFormData() {
            let formType = this.processConfig.formType;
            let rxForms = this.$refs.rxForms;
            if (formType == "online" && rxForms) {
                this.formDataJson = rxForms.getData();
            }
            this.isShowImage = true;
        },
        i18n(name, text, key) {
            return this.$ti18(name, text, "bpmInst", key);
        },
        initParams() {
            //从属性传入，这个一般用于 Util.open的方式打开。
            if (this.defId) {
                this.localDefId = this.defId;
                this.initProcessConfig();
            }
            //从弹框打开,使用DialogView 打开
            else if (this.menuParams) {
                this.handParams(JSON.parse(this.menuParams));
            } else if (this.config) {
                if (this.config.defId) {
                    this.localDefId = this.config.defId;
                }
                if (this.config.defKey) {
                    this.defKey = this.config.defKey;
                }
                this.initProcessConfig();
            }
            //通过路由获取参数
            else {
                var params;
                if (this.$route.meta.params) {
                    params = JSON.parse(this.$route.meta.params);
                } else {
                    params = this.$route.params;
                }
                this.fromRoute = true;
                this.handParams(params);
            }

        },
        handParams(params) {
            if (params.defId) {
                this.localDefId = params.defId;
            }
            if (params.defKey) {
                this.defKey = params.defKey;
            }
            this.initProcessConfig();
        },
        initProcessConfig() {
            var self_ = this;
            BpmInstApi.getProcessConfig(this.localDefId, this.defKey,this.appId).then(res => {
                if (!res.success) {
                    this.$message.warning(res.message);
                    return;
                }
                self_.localDefId = res.data.defId;
                self_.version = res.data.version;

                if (res.data) {
                    var config = Util.deepClone(self_.processConfig);
                    let buttonConfigs = [];
                    for (let i = 0; i < res.data.buttonConfigs.length; i++) {
                        //启动去除特送按钮
                        if (res.data.buttonConfigs[i].type != "specialDelivery") {
                            buttonConfigs.push(res.data.buttonConfigs[i]);
                        }
                    }
                    res.data.buttonConfigs = buttonConfigs;
                    self_.processConfig = Object.assign(config, res.data);
                }
                //处理表单配置。
                self_.handFormConfig(res.data);
                //加载表单。
                if (self_.processConfig.formType == "online") {
                    self_.initForm();
                }
                else {
                    self_.initCustomForm();
                }
            })
        },
        /**
         * 初始化自定义表单，主要是加载主键.
         */
        initCustomForm() {
            let instId_ = this.instId ? this.instId : this.$route.params.instId;
            if (!instId_) {
                if (this.config && this.config.instId) {
                    instId_ = this.config.instId;
                }
            }
            if (!instId_) {
                return;
            }
            BpmInstApi.getPkByInstId(instId_).then(res => {
                if (!res.success) {
                    return;
                }
                this.pk = res.data;
            })
        },
        //处理表单配置。
        handFormConfig(conf) {
            //startForm
            let startForm = conf.startForm.formpc;
            if (startForm && startForm.length > 0) {
                var form = startForm[0];
                this.handCustomForm(form);
            }
            //获取全局。
            let globalForm = conf.globalForm.formpc;
            if (globalForm && globalForm.length > 0) {
                var form = globalForm[0];
                this.handCustomForm(form);
            }
        },
        /**
         * 处理自定义表单和外部URL表单.
         * @param form
         */
        handCustomForm(form){
            if (form && form.type == "custom") {
                this.processConfig.formType = "custom";
                this.formComponent = AppUtil.loadComponent(form.component);
                this.handFormParams(form.id);
                return;
            }
            if (form && form.type == "outsideUrl") {
                this.outSideUrl = form.component;
                this.processConfig.formType = "outsideUrl";
                this.handFormParams(form.id);
            }
        },
        handFormParams(formId){
            var contextData = {
                defId: this.localDefId,
                instId: this.instId,
                stageType: "start",
            }
            this.handUrlParams(formId,contextData);
        },
        async initForm() {
            var params = {defId: this.localDefId};
            var instId = this.instId ? this.instId : this.$route.params.instId;
            if (instId) {
                params.instId = instId;
            }

            //如果从外部传入主键
            if (this.pkId) {
                params.pkId = this.pkId;
            }

            let res = await BpmInstApi.getViewByDefId(params);

            if (!res.success) {
                this.$message.warning(res.message);
                return;
            }
            var data = res.data;
            var formData = data.formData;


            var curUser = this.user;
            var contextData = {
                type: "start",
                curUserId: curUser.userId,
                curUserName: curUser.fullName,
                account: curUser.account,
                deptId: curUser.deptId,
                curNodeId: "start",
                curNodeName: this.i18n('list.startNode', '开始节点'),
                instId: this.instId,
                defId: this.localDefId,
                tenantId: curUser.tenantId,
                tenantLabel: curUser.tenantLabel,
                subject:this.processConfig.name,
                //当前是否为发起人
                starter:true,
            };

            formData[0].data = Object.assign(formData[0].data, this.formData);
            this.$refs.rxForms.setData(formData, false, contextData);
            //表单数据设置完成，更新按钮权限计算
            if(this.$refs.processToolBar){
                this.$nextTick(()=>{
                    this.$refs.processToolBar.updateBtnAuth();
                });
            }
        },
        closeWindow() {
            if (this.fromRoute) {
                this.$bus.emit("closeTab", {action: "current"})
            } else {
                Util.closeWindow(this, 'ok');
            }
        },
        bpmPreview() {
            Util.open({
                component: BpmImageView,
                curVm: this,
                title: this.i18n('list.processSimu', '流程仿真'),
                widthHeight: ['1024px', '600px'],
                data: {
                    defId: this.localDefId,
                    preview: true,
                    startUserId: this.startUserId,
                    formData: this.$refs.rxForms ? this.$refs.rxForms.getData() : {}
                }
            }, function (action) {
            });
        }
    },
    watch: {
        closed: function (val) {
            if (val) {
                this.closeWindow();
            }
        },
        '$route': {
            handler: function (val) {
                if(val.name==='appHome'){
                  return;
                }
                this.initParams();
            },
            deep: true
        }
    }
}
</script>
<style scoped>
.tabs-toolbar {
    display: inline-block;
    padding-right: 10px;
}
.rx-bpm-tabs ::v-deep(.ant-tabs-nav){
    padding-left: 20px;
    margin-bottom: 0;
}
.tab-center-bg {
    width: 100%;
    background: #F5F5F5;
    overflow: auto;
    height: calc(100vh - 96px);
}

.tab-center {
    box-sizing: border-box;
    padding-top: 10px;
    max-width: 1300px;
    width: 80%;
    margin:10px auto;
    min-height: calc(100vh - 121px);
    background: #fff;
    border-radius: 4px;
}

.rx-bpm-tabs ::v-deep(.ant-tabs-bar.ant-tabs-top-bar) {
    margin-bottom: 0 !important;
}
.tab-center-box ::v-deep(.x-form-build-box)::-webkit-scrollbar-corner{
    background-color: transparent;
}
.tab-center-box{
    height: inherit;
}

</style>

